package problem03;

import java.util.Stack;

/**
 * 问题3，只是用递归和栈操作来逆序一个栈
 * @author Administrator
 *
 */
public class ReverseStack {

	
	private static int getAndRemoveLastElement(Stack<Integer> stack) {
		if(stack.isEmpty())
			throw new RuntimeException("栈为空！");
		Integer pop = stack.pop();
		if(stack.isEmpty())
			return pop;
		int i =getAndRemoveLastElement(stack, pop);
		return i;
		
	}
	private static int getAndRemoveLastElement(Stack<Integer> stack,int a) {
		Integer pop = stack.pop();
		if(stack.isEmpty()){
			stack.push(a);
			return pop;
		}
		int i = getAndRemoveLastElement(stack, pop);
		stack.push(a);
		return i;
	}
	

	/**
	 * 
	 * @param stack
	 */
	public static void reverseStackByRecursion(Stack<Integer> stack) {
		if(stack.isEmpty()){
			return;
		}
		int i =getAndRemoveLastElement(stack);
		reverseStackByRecursion(stack);
		stack.push(i);
	}
	
	//测试
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		System.out.println(stack);
		ReverseStack.reverseStackByRecursion(stack);
		System.out.println(stack);
		
		
	}
}
